package com.mzy.javaapi.String;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author mzy
 * @Date 2022/4/13 10:45
 * @Version 1.0
 */
public class substring {

    /**
     * 按照特定字符分割获取最后的几个字符
     * @param args
     */

    /**
     * Created with IntelliJ IDEA.
     * @Author ${USER}
     * @Date ${DATE} ${TIME}
     * @Version 1.0
     */
    public static void main(String[] args) {
        String imgUrl = "http://127.0.0.1:8080/cms/ReadAddress/1479805098158.jpg";

        String substring = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
        System.out.println(substring);
    }





    /**
     * 通过文件名和文件路径下载指定文件
     *
     * @param response
     * @param folderName
     * @param fileName
     */
    public static void downloadFile(HttpServletResponse response, String folderName, String fileName) {

        try {

            String logPath = folderName + File.separator + fileName;
            // 读文件
            File file = new File(logPath);
            // 重置response
            response.reset();
            // ContentType，即告诉客户端所发送的数据属于什么类型
            response.setContentType("application/octet-stream; charset=UTF-8");
            // 获得文件的长度
            response.setHeader("Content-Length", String.valueOf(file.length()));
            // 设置编码格式
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

            // 发送给客户端的数据
            try (OutputStream outputStream = response.getOutputStream();
                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {

                byte[] buff = new byte[1024];
                int i = bis.read(buff);
                // 只要能读到，则一直读取
                while (i != -1) {
                    // 将文件写出
                    outputStream.write(buff, 0, buff.length);
                    // 刷出
                    i = bis.read(buff);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
//            log.error("下载文件异常", e);
            System.out.println("下载文件异常");
        } finally {

        }
    }
}
